

package com.l2qq.admin.role;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.l2qq.common.model.Permission;
import com.l2qq.common.model.Role;
import com.l2qq.common.model.RolePermission;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 角色管理
 */
public class RoleAdminService {

    private static final int pageSize = 25;
    @Inject
	Role roleDao;

    public Page<Role> paginate(int pageNum, int pageSize) {
        return roleDao.template("my.assignRolesListVue").paginate(pageNum, pageSize);
        //return dao.paginate(pageNum, pageSize, "select *", "from role order by id asc");
    }

    public Role findById(int roleId) {
        return roleDao.findById(roleId);
    }

    public List<Role> getAllRoles() {
        return roleDao.template("my.assignRolesListVue").find();
        //return dao.find("select * from role order by id asc");
    }

    /**
     * 判断角色名是否存在
     * @param roleId 当前 role 对象的 id 号，如果 role 对象还未创建，提供一个小于 0 的值即可
     * @param name 角色名
     */
    public boolean exists(long roleId, String name) {
        name = name.toLowerCase().trim();
        String sql = "select id from role where lower(name) = ? and id != ? limit 1";
        Integer id = Db.queryInt(sql, name, roleId);
        return id != null;
    }

    /**
     * 创建角色
     */
    public Ret save(Role role) {
        if (exists(-1, role.getName())) {
            return Ret.fail("msg", "角色名称已经存在，请输入别的名称");
        }
        role.setName(role.getName().trim());
        role.setCreateDate(new Date());
        role.remove("id").save();
        return Ret.ok("msg", "创建成功");
    }

    public Ret saveVue(Role role) {
        if (exists(-1, role.getName())) {
            return Ret.fail("msg", "角色名称已经存在，请输入别的名称");
        }

        role.setName(role.getName().trim());
        role.setCreateDate(new Date());
        role.remove("id").save();
        return Ret.ok("msg", "创建成功");
    }

    /**
     * 更新角色
     */
    public Ret update(Role role, String[] roleSubject) {
        Ret ret = Ret.ok("msg", "角色更新成功");
        boolean b = Db.tx(() -> {
            if (role.getId() == 1) {
                ret.setFail().set("msg", "超级管理员不能被修改");
                return false;
            }
		   /* Role roleDb = dao.findById(role.getId());
			if (!roleDb.getIsAbleChange()) {
				ret.setFail().set("msg", "该角色不能修改!");
				return false;
			}*/
            if (exists(role.getId(), role.getName())) {
                ret.setFail().set("msg", "角色名称已经存在，请输入别的名称");
                return false;
            }
            role.setName(role.getName().trim());
            boolean bRole = role.update();
            if (bRole) {
                Db.update("delete from role_subject WHERE role_id = ? ", role.getId());
                role.update();
            }
            return bRole;
        });
        return ret;
    }


    public Ret updateVue(Role role) {
        if (role.getId() == 1) {
            return Ret.fail("msg", "超级管理员不能被修改");
        }

        if (exists(role.getId(), role.getName())) {
            return Ret.fail("msg", "角色名称已经存在，请输入别的名称");
        }

        role.setName(role.getName().trim());
        role.update();
        return Ret.ok("msg", "角色更新成功");
    }

    public Ret delete(final int roleId) {
        if (roleId == 1) {
            return Ret.fail("msg", "超级管理员不能被删除");
        }

        Db.tx(() -> {
            Db.delete("delete from account_role where role_id = ?", roleId);
            Db.delete("delete from role_permission where role_id = ?", roleId);
            roleDao.deleteById(roleId);
            return true;
        });

        return Ret.ok("msg", "角色删除成功");
    }


    public Ret deleteVue(final int roleId) {
        if (roleId == 1) {
            return Ret.fail("msg", "超级管理员不能被删除");
        }

        Db.tx(() -> {
            Db.delete("delete from account_role where role_id = ?", roleId);
            Db.delete("delete from role_permission where role_id = ?", roleId);
            roleDao.deleteById(roleId);
            return true;
        });

        return Ret.ok("msg", "角色删除成功");
    }

    /**
     * 添加权限
     */
    public Ret addPermission(int roleId, int permissionId) {
        if (roleId == 1) {
            return Ret.fail("msg", "超级管理员天然拥有所有权限，无需分配");
        }
        RolePermission rolePermission = new RolePermission();
        rolePermission.setPermissionId(permissionId);
        rolePermission.setRoleId(roleId);
        rolePermission.save();
        //Record rolePermission = new Record().remove("id").set("role_id", roleId).set("permission_id", permissionId);
        //Db.save("role_permission", rolePermission);
        return Ret.ok("msg", "添加权限成功");
    }

    /**
     * 删除权限
     */
    public Ret deletePermission(int roleId, int permissionId) {
        if (roleId == 1) {
            return Ret.fail("msg", "超级管理员天然拥有所有权限，不能删除权限");
        }

        Db.delete("delete from role_permission where role_id = ? and permission_id = ?", roleId, permissionId);
        return Ret.ok("msg", "删除权限成功");
    }

    /**
     * 标记出 role 拥有的权限，用于在界面输出 checkbox 的 checked 属性
     * 未来用 permission left join role_permission 来优化
     */
    public void markAssignedPermissions(Role role, List<Permission> permissionList) {
        // id 为 1 的超级管理员默认拥有所有权限
        if (role.getId() == 1) {
            for (Permission permission : permissionList) {
                permission.put("assigned", true);
            }
            return;
        }

        String sql = "select role_id from role_permission where role_id = ? and permission_id=? limit 1";
        for (Permission permission : permissionList) {
            Integer roleId = Db.queryInt(sql, role.getId(), permission.getId());
            if (roleId != null) {
                // 设置 assigned 用于界面输出 checked
                permission.put("assigned", true);
            }
        }
    }

    /**
     * 根据 controller 将 permission 进行分组
     */
    public LinkedHashMap<String, List<Permission>> groupByController(List<Permission> permissionList) {
        LinkedHashMap<String, List<Permission>> ret = new LinkedHashMap<String, List<Permission>>();

        for (Permission permission : permissionList) {
            String controller = permission.getController();
            List<Permission> list = ret.get(controller);
            if (list == null) {
                list = new ArrayList<Permission>();
                ret.put(controller, list);
            }

            list.add(permission);
        }

        return ret;
    }
}
